package de.freudenreichdesign.webshop.controller;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import de.freudenreichdesign.webshop.model.Customer;
import de.freudenreichdesign.webshop.service.AccountService;

@Controller
@RequestMapping("/editUserData.html")
public class EditUserDataController{

	public EditUserDataController() {}
	
	@RequestMapping(method=RequestMethod.GET)
	public String showForm(ModelMap modelMap) {
		Customer customer = AccountService.getInstance().getCustomerByID(1);
		modelMap.addAttribute(customer);
		return "editUserDataView";
	}
	
	@RequestMapping(method=RequestMethod.POST)
	public String onSubmit(@ModelAttribute("customer") Customer customer) {
		System.out.println(customer.getCustomerID());
		AccountService.getInstance().changeCustomerData(1,
				customer.getPerson().getTitle(), 
				customer.getPerson().getGender(),
				customer.getPerson().getFirstName(),
				customer.getPerson().getLastName(),
				customer.getPerson().geteMail(),
				customer.getPerson().getPhoneNumber(),
				customer.getDateOfBirth());
		return "redirect:/editUserData.html?updateStatus=success";
	}
	
	@InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }

}
